import { useCallback } from "react";
import { message } from "antd";
import { useRouter } from "next/navigation";

interface CrudOperationsOptions {
  deleteFunction?: (id: number) => Promise<{ success: boolean; error?: string }>;
  onDeleteSuccess?: () => void;
  onDeleteError?: (error: unknown) => void;
  deleteSuccessMessage?: string;
  deleteErrorMessage?: string;
}

interface CrudOperationsReturn {
  handleDelete: (id: number) => Promise<void>;
  handleAdd: (path: string) => void;
  handleEdit: (path: string, id: number) => void;
  handlePreview: (path: string, slug: string) => void;
}

export function useCrudOperations({ deleteFunction, onDeleteSuccess, onDeleteError, deleteSuccessMessage = "删除成功", deleteErrorMessage = "删除失败" }: CrudOperationsOptions = {}): CrudOperationsReturn {
  const router = useRouter();

  const handleDelete = useCallback(
    async (id: number) => {
      if (!deleteFunction) {
        console.warn("删除函数未提供");
        return;
      }

      try {
        const response = await deleteFunction(id);
        if (response.success) {
          message.success(deleteSuccessMessage);
          onDeleteSuccess?.();
        } else {
          message.error(response.error || deleteErrorMessage);
          onDeleteError?.(response.error);
        }
      } catch (error) {
        console.error("删除操作失败:", error);
        message.error(deleteErrorMessage);
        onDeleteError?.(error);
      }
    },
    [deleteFunction, onDeleteSuccess, onDeleteError, deleteSuccessMessage, deleteErrorMessage]
  );

  const handleAdd = useCallback(
    (path: string) => {
      router.push(path);
    },
    [router]
  );

  const handleEdit = useCallback(
    (path: string, id: number) => {
      router.push(`${path}?id=${id}`);
    },
    [router]
  );

  const handlePreview = useCallback((path: string, slug: string) => {
    window.open(`${path}/${slug}`, "_blank");
  }, []);

  return {
    handleDelete,
    handleAdd,
    handleEdit,
    handlePreview,
  };
}
